package com.wsc.indexer.utils;

import java.io.StringReader;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class XMLHandler {

	Document doc;
	
	// Construct XML Document from String.
	
	public Document loadXMLFromString(String xml) throws Exception
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        
        InputSource is = new InputSource(new StringReader(xml));
        
        this.doc = builder.parse(is);;
        
        return doc;
    }
	
	
	public ArrayList<Object> parseURLS(){
		
		// Normalize the document, to avoid simple parsing errors.
		
		doc.getDocumentElement().normalize();
		
		ArrayList<Object> urls =new ArrayList<Object>();
		
		NodeList list=doc.getElementsByTagName("url");
		
		System.out.println("Length of the list:"+list.getLength());
		
		for(int i=0; i < list.getLength(); i++){
			
			Node node=list.item(i);
			
			System.out.println(node);
			
			urls.add(node);
			
		}
		return urls;
	}
	
	
	public static void main(String...s){
		
		XMLHandler h=new XMLHandler();
		
		String xml="<?xml version=\"1.0\" ?>" +
				"<urls><url>abc</url><url>abc</url></urls>";
		
		try {
			h.loadXMLFromString(xml);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		h.parseURLS();
	}
}
